package com.example.demo.controller;

import com.example.demo.model.Job;
import com.example.demo.service.JobService;
import com.example.demo.util.Res;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Description 描述
 * @Date 2021-01-13 5:07 下午
 * @Author wuyanshen
 */
@Slf4j
@RequestMapping("/job")
@RestController
public class JobController {

    @Autowired
    private JobService jobService;

    @Autowired
    private Scheduler scheduler;

    @GetMapping("/all")
    public List<Job> list() {
        return jobService.all();
    }

    @PostMapping("/saveOrUpdate")
    public Res add(@RequestBody Job job) {
        if (ObjectUtils.isEmpty(job.getId())) {
            log.info(String.format("新增任务 【 %s 】", job.getJobName()));
        } else {
            log.info(String.format("修改任务 【 %s 】", job.getJobName()));
        }
        jobService.saveJob(job);
        return Res.success("新增job成功");
    }


    @DeleteMapping("/delete")
    public Res delete(@RequestBody Job job) {
        log.info(String.format("删除任务 【 %s 】", job.getJobName()));
        jobService.delete(job);
        return Res.success("删除任务成功");
    }

    /**
     * 手动执行一次任务
     * @param job
     * @return
     */
    @PostMapping("/trigger")
    public Res trigger(@RequestBody Job job) {
        log.info(String.format("手动执行任务 【 %s 】", job.getJobName()));
        try {
            JobKey key = new JobKey(job.getJobName());
            scheduler.triggerJob(key);
        } catch (Exception e) {
            return Res.fail(e.getMessage());
        }
        return Res.success("手动执行任务成功");
    }

    /**
     * 停止任务
     * @param job
     * @return
     */
    @PostMapping("/pause")
    public Res pause(@RequestBody Job job) {
        log.info(String.format("停止任务 【 %s 】", job.getJobName()));
        try {
            JobKey key = new JobKey(job.getJobName());
            scheduler.pauseJob(key);
            // 更新sys_job表任务状态
            jobService.update(job);
        } catch (Exception e) {
            return Res.fail(e.getMessage());
        }
        return Res.success("停止任务成功");
    }

    /**
     * 恢复任务
     * @param job
     * @return
     */
    @PostMapping("/resume")
    public Res resume(@RequestBody Job job) {
        log.info(String.format("恢复任务 【 %s 】", job.getJobName()));
        try {
            JobKey key = new JobKey(job.getJobName());
            scheduler.resumeJob(key);
            // 更新sys_job表任务状态
            jobService.update(job);
        } catch (Exception e) {
            return Res.fail(e.getMessage());
        }
        return Res.success("恢复任务成功");
    }


}
